package com.ruoyi.kis.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult_KIS;
import com.ruoyi.common.utils.DateUtils;
//import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.annotaion.BasicAuthCheck;
import com.ruoyi.kis.domain.*;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.HttpSendWmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.util.*;

@RestController
@RequestMapping("/kis")
@Component("kis")
@Api("物料同步")
public class KisApiController {

    @Autowired
    private IKisService kisService;
    @Autowired
    private HttpSendWmsUtil httpSendWmsUtil;
    private static final Logger LOGGER = LoggerFactory.getLogger(KisApiController.class);


    /**
     * 销售出库单（已废弃使用，对应接口在【发货通知单类：KisFhtzController/】）
     */
    @ApiOperation("销售出库单")
    @RequestMapping("/outwareorder")
    public AjaxResult_KIS outwareorder(){
        Date orderTime = kisService.queryCurrentTime(Constants.OUTBOUND_DELIVERY_ORDER);
        List<OutboundDelveryOrderF> outboundDelveryOrderFList = kisService.queryOutboundDelveryOrderF(orderTime);
        Optional<OutboundDelveryOrderF> maxRecord = outboundDelveryOrderFList.stream()
                .max(Comparator.comparing(OutboundDelveryOrderF::getFDate ));

        if (maxRecord.isPresent()) {
            OutboundDelveryOrderF maxTimeRecord = maxRecord.get();
            final Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,maxTimeRecord.getFDate() );
            Map<String,Object> params = new HashMap<>();
            params.put("tableName",Constants.OUTBOUND_DELIVERY_ORDER);
            params.put("fLastUpdateTime",date);
            kisService.updateCurrentTime(params);
            LOGGER.info("时间最大的记录是：{}" , date);
        } else {
            LOGGER.info("List为空，没有最大的记录");
        }

        return AjaxResult_KIS.success("OK",outboundDelveryOrderFList);
    }

    /**
     * 已废弃，对接调拨单在类：KisZjdbdController
     * @return
     */
    @ApiOperation("调拨单")
    @RequestMapping("/transferorder")
    public AjaxResult_KIS transferOrder(){
//        Date orderTime = kisService.queryCurrentTime(Constants.TRANSFER_ORDER);
//        List<TransferOrderF> transferOrderFList = kisService.queryTransferOrderF(orderTime);
        List<TransferOrderF> transferOrderFList = kisService.queryTransferOrderF();
        Optional<TransferOrderF> maxRecord = transferOrderFList.stream()
                .max(Comparator.comparing(TransferOrderF::getFDate ));

        if (maxRecord.isPresent()) {
            TransferOrderF maxTimeRecord = maxRecord.get();
            final Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,maxTimeRecord.getFDate() );
            Map<String,Object> params = new HashMap<>();
            params.put("tableName",Constants.TRANSFER_ORDER);
            params.put("fLastUpdateTime",date);
            kisService.updateCurrentTime(params);
            System.out.println("时间最大的记录是：" + date);
        } else {
            System.out.println("List为空，没有最大的记录");
        }
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("FEntity", transferOrderFList);
        ObjectMapper mapper = new ObjectMapper();
//        mapper.setPropertyNamingStrategy(PropertyNamingStrategies.UPPER_CAMEL_CASE);
        mapper.configure(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID, true); // 例如，重置日期格式设置

        try {
            String jsonString = mapper.writeValueAsString(jsonMap);
//            String msg = HttpUtils.sendPost(Constants.T_ICITEMS_URL,jsonString);
            String post = HttpUtil.post(Constants.TRANSFER_ORDER_URL, jsonString);
            LOGGER.info(post);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return AjaxResult_KIS.success("OK",transferOrderFList);
    }

    /**
     * 基础物料数据同步
     * @return
     */
    @ApiOperation("物料信息同步")
    @RequestMapping("/synmaterialdata")
    public AjaxResult_KIS synMaterialData(){
        Date orderTime = kisService.queryCurrentTime(Constants.T_ICITEMS);
        List<IcItems> icItemsList = kisService.queryICITEMS(orderTime);
        Optional<IcItems> maxRecord = icItemsList.stream()
                .max(Comparator.comparing(IcItems::getFLastUpdateTime ));

        if (maxRecord.isPresent()) {
            IcItems maxTimeRecord = maxRecord.get();
//            final Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,maxTimeRecord.getFLastUpdateTime() );
            final Date date = maxTimeRecord.getFLastUpdateTime();
            Map<String,Object> params = new HashMap<>();
            params.put("tableName",Constants.T_ICITEMS);
            params.put("fLastUpdateTime",date);
            kisService.updateCurrentTime(params);
            LOGGER.info("时间最大的记录是：{}" , maxTimeRecord.getFLastUpdateTime());
        } else {
            LOGGER.info("List为空，没有最大的记录");
        }
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("FEntity", icItemsList);
        ObjectMapper mapper = new ObjectMapper();
//        mapper.setPropertyNamingStrategy(PropertyNamingStrategies.UPPER_CAMEL_CASE);
        mapper.configure(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID, true); // 例如，重置日期格式设置
        try {
            // TODO 无值不需要请求接口
            String jsonString = mapper.writeValueAsString(jsonMap);
            String post = httpSendWmsUtil.sendWms(Constants.T_ICITEMS_URL,jsonString);
            LOGGER.info("物料基础数据同步反馈:{},记录物料条数：{}",post,icItemsList.size());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return AjaxResult_KIS.success("OK",icItemsList);
    }

}
